import { useState, useEffect, useRef } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Input, Button, Avatar, Spin, message, Tooltip, Tag } from "antd";
import {
  SendOutlined,
  ArrowDownOutlined,
  SaveOutlined,
  UserOutlined,
  EyeOutlined,
  EditOutlined,
  LeftCircleFilled,
} from "@ant-design/icons";
import { generateContent, saveAIHistory } from "../../services/chat";
import { ChatMessage, ChatRequest, Message } from "../../types";
import { useAgentStore, useChatHistoryStore } from "../../context";
import styles from "./Chat.module.scss";

// 导入 Markdown 相关库
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

const Chat = () => {
  const { agentId } = useParams<{ agentId: string }>();
  const navigate = useNavigate();

  // 从 Context 获取 Agent 状态
  const selectedAgent = useAgentStore((state) => state.selectedAgent);
  const setSelectedAgent = useAgentStore((state) => state.setSelectedAgent);

  // 从 Context 获取历史聊天状态
  const selectedHistory = useChatHistoryStore((state) => state.selectedHistory);
  const clearSelectedHistory = useChatHistoryStore(
    (state) => state.clearSelectedHistory
  );
  const addMessageToHistory = useChatHistoryStore(
    (state) => state.addMessageToHistory
  );

  const [messages, setMessages] = useState<Message[]>([]);
  const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);
  const [inputValue, setInputValue] = useState("");
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);
  const [showScrollButton, setShowScrollButton] = useState(false);
  const [savingHistory, setSavingHistory] = useState(false);
  const [readOnly, setReadOnly] = useState(false);
  const [isEditMode, setIsEditMode] = useState(true);
  const [savedHistoryId, setSavedHistoryId] = useState<string | null>(null);

  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<any>(null);

  // 初始化聊天 - 处理 Agent 信息和历史聊天
  useEffect(() => {
    const initializeChat = async () => {
      try {
        // 首先检查是否有已选择的历史聊天记录
        if (selectedHistory && selectedHistory.history) {
          // 确保历史记录是数组
          const historyArray: {role: string; message: string}[] = Array.isArray(selectedHistory.history) 
            ? selectedHistory.history 
            : JSON.parse(selectedHistory.history || '[]');
          
          // 如果有历史记录，使用历史记录中的消息
          setMessages(
            historyArray.map((item: {role: string; message: string}) => ({
              id: Date.now() + Math.random() + "",
              content: item.message,
              isUser: item.role !== "assistant" && item.role !== "system",
              timestamp: new Date(),
            }))
          );

          // 从历史记录中构建聊天历史
          const chatHistoryFromMessages = historyArray.map(
            (msg: {role: string; message: string}) => ({
              role: msg.role,
              message: msg.message,
            })
          );

          setChatHistory(chatHistoryFromMessages);

          // 设置历史记录ID
          if (selectedHistory.id) {
            setSavedHistoryId(selectedHistory.id + "");
          }

          // 默认设置为只读模式
          setReadOnly(true);
          setIsEditMode(false);

          // 如果历史记录中有关联的 Agent，确保它被选中
          if (
            selectedHistory.agentId &&
            (!selectedAgent ||
              selectedAgent.ID.toString() !== selectedHistory.agentId)
          ) {
            // 简化处理：如果没有获取 Agent 的 API，可以直接使用当前选中的 Agent
            if (selectedAgent) {
              setLoading(false);
            } else {
              message.error("无法恢复聊天，未找到相关 AI 助手");
              navigate("/agents");
              return;
            }
          } else {
            setLoading(false);
          }
        }
        // 如果没有历史记录，检查是否有选中的 Agent
        else if (selectedAgent && selectedAgent.ID.toString() === agentId) {
          // 添加系统提示到聊天历史
          if (selectedAgent?.SysHint) {
            setChatHistory([
              {
                role: "system",
                message: selectedAgent.SysHint,
              },
            ]);
          }

          // 添加欢迎消息
          setMessages([
            {
              id: "1",
              content: `你好，我是${selectedAgent.AIName}，有什么我可以帮助你的吗？`,
              isUser: false,
              timestamp: new Date(),
            },
          ]);

          setLoading(false);
          setReadOnly(false);
          setIsEditMode(true);
        } else {
          // 如果既没有历史记录也没有匹配的 Agent，返回 agents 页面
          message.error("未找到 AI 助手信息，请重新选择");
          navigate("/agents");
          return;
        }

        // 聊天页面加载完成后，自动聚焦到输入框（如果不是只读模式）
        setTimeout(() => {
          if (!readOnly && inputRef.current) {
            inputRef.current.focus();
          }
        }, 300);
      } catch (error) {
        console.error("初始化聊天失败:", error);
        message.error("初始化聊天失败，请重试");
        setLoading(false);
      }
    };

    initializeChat();

    // 组件卸载时清除选中的历史记录
    return () => {
      clearSelectedHistory();
    };
  }, [
    agentId,
    selectedAgent,
    selectedHistory,
    navigate,
    setSelectedAgent,
    clearSelectedHistory,
  ]);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 确保在加载完成后也滚动到底部
  useEffect(() => {
    if (!loading) {
      scrollToBottom();
    }
  }, [loading]);

  // 监听滚动事件
  useEffect(() => {
    const messagesContainer = document.querySelector(
      `.${styles.messagesContainer}`
    );

    const handleScroll = () => {
      if (messagesContainer) {
        const { scrollTop, scrollHeight, clientHeight } = messagesContainer;
        // 如果距离底部超过200px，显示滚动按钮
        setShowScrollButton(scrollHeight - scrollTop - clientHeight > 200);
      }
    };

    messagesContainer?.addEventListener("scroll", handleScroll);
    return () => messagesContainer?.removeEventListener("scroll", handleScroll);
  }, []);

  const scrollToBottom = () => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  };

  const handleSendMessage = async () => {
    if (!inputValue.trim() || sending || !selectedAgent || readOnly) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      content: inputValue,
      isUser: true,
      timestamp: new Date(),
    };

    // 更新UI消息列表
    setMessages((prev) => [...prev, userMessage]);

    // 如果是从历史记录恢复的聊天并且处于编辑模式，也更新历史记录
    if (selectedHistory && isEditMode) {
      addMessageToHistory(userMessage);
    }

    // 更新聊天历史
    const updatedHistory = [
      ...chatHistory,
      { role: "user", message: inputValue },
    ];
    setChatHistory(updatedHistory);

    setInputValue("");
    setSending(true);

    try {
      // 准备请求数据
      const chatRequest: ChatRequest = {
        model: "gpt-4o", // 可以根据需要修改模型
        id: selectedAgent.ID,
        history: updatedHistory,
      };

      // 发送请求到服务器
      const response = await generateContent(chatRequest);

      // 创建AI回复消息
      const aiMessage: Message = {
        id: (Date.now() + 1).toString(),
        content: response.content,
        isUser: false,
        timestamp: new Date(),
      };

      // 更新UI消息列表
      setMessages((prev) => [...prev, aiMessage]);

      // 如果是从历史记录恢复的聊天并且处于编辑模式，也更新历史记录
      if (selectedHistory && isEditMode) {
        addMessageToHistory(aiMessage);
      }

      // 更新聊天历史
      setChatHistory([
        ...updatedHistory,
        { role: "assistant", message: response.content },
      ]);
    } catch (error) {
      console.error("发送消息失败:", error);
      message.error("发送消息失败，请重试");
    } finally {
      setSending(false);
    }
  };

  const handleSaveHistory = async () => {
    if (!selectedAgent || messages.length <= 1) {
      message.info("没有足够的对话内容可保存");
      return;
    }

    setSavingHistory(true);
    try {
      // 准备保存的历史记录数据
      const historyData = savedHistoryId
        ? {
            id: selectedAgent.ID,
            history: JSON.stringify(
              messages?.map((item) => ({
                role: item.isUser ? "user" : "assistant",
                message: item.content,
              }))
            ),
            uuid: savedHistoryId,
          }
        : {
            id: selectedAgent.ID,
            history: JSON.stringify(
              messages?.map((item) => ({
                role: item.isUser ? "user" : "assistant",
                message: item.content,
              }))
            ),
          };

      // 调用保存接口
      const response = await saveAIHistory(historyData);

      // 如果是新创建的历史记录，保存返回的ID
      if (response && response.data && !savedHistoryId) {
        setSavedHistoryId(response.data);
        message.success("聊天记录保存成功");
      } else {
        message.success(
          savedHistoryId ? "聊天记录更新成功" : "聊天记录保存成功"
        );
      }
    } catch (error) {
      console.error("保存聊天记录失败:", error);
      message.error("保存聊天记录失败，请重试");
    } finally {
      setSavingHistory(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey && !readOnly) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 切换编辑/只读模式
  const toggleEditMode = () => {
    if (selectedHistory) {
      setIsEditMode(!isEditMode);
      setReadOnly(!isEditMode);

      // 如果切换到编辑模式，聚焦到输入框
      if (readOnly && inputRef.current) {
        setTimeout(() => {
          inputRef.current.focus();
        }, 100);
      }
    }
  };

  // 渲染消息内容，支持简单的 Markdown
  const renderMessageContent = (content: string, isUser: boolean) => {
    if (isUser) {
      // 用户消息保持纯文本
      return <div className={styles.messageBubble}>{content}</div>;
    } else {
      // AI 消息支持 Markdown 渲染
      return (
        <div className={`${styles.messageBubble} ${styles.markdownContent}`}>
          <ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
        </div>
      );
    }
  };

  return (
    <div className={styles.chatContainer}>
      {loading ? (
        <div className={styles.loading}>
          <Spin size="large" />
        </div>
      ) : (
        <>
          <div className={styles.chatHeader}>
            <Button
              icon={<LeftCircleFilled />}
              type="text"
              onClick={() => navigate(-1)}
              className={styles.backButton}
            />
            <h2>{selectedAgent?.AIName}</h2>

            {selectedHistory && (
              <Tag
                color={isEditMode ? "green" : "blue"}
                className={styles.modeTag}
              >
                {isEditMode ? "编辑模式" : "只读模式"}
              </Tag>
            )}

            {isEditMode && (
              <div className={styles.headerActions}>
                {selectedHistory && (
                  <Tooltip
                    title={isEditMode ? "切换到只读模式" : "切换到编辑模式"}
                  >
                    <Button
                      icon={isEditMode ? <EyeOutlined /> : <EditOutlined />}
                      type="text"
                      onClick={toggleEditMode}
                      className={styles.modeButton}
                    />
                  </Tooltip>
                )}

                <Tooltip
                  title={savedHistoryId ? "更新聊天记录" : "保存聊天记录"}
                >
                  <Button
                    icon={<SaveOutlined />}
                    type="text"
                    onClick={handleSaveHistory}
                    loading={savingHistory}
                    className={styles.saveButton}
                    disabled={messages.length <= 1 || (readOnly && !isEditMode)}
                  >保存会话</Button>
                </Tooltip>
              </div>
            )}
          </div>

          <div
            className={`${styles.messagesContainer} ${styles.hasMultipleMessages}`}
          >
            {messages.map((message) => (
              <div
                key={message.id}
                className={`${styles.messageWrapper} ${
                  message.isUser ? styles.userMessage : styles.aiMessage
                }`}
              >
                <div className={styles.messageContent}>
                  {!message.isUser && (
                    <Avatar
                      src={selectedAgent?.AIAvatar}
                      size={48}
                      className={styles.messageAvatar}
                    />
                  )}
                  {renderMessageContent(message.content, message.isUser)}
                  {message.isUser && (
                    <Avatar
                      icon={<UserOutlined />}
                      size={48}
                      className={styles.messageAvatar}
                    />
                  )}
                </div>
                {!!message?.timestamp && (
                  <div className={styles.messageTime}>
                    {message.timestamp.toLocaleTimeString([], {
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </div>
                )}
              </div>
            ))}
            {sending && (
              <div className={`${styles.messageWrapper} ${styles.aiMessage}`}>
                <div className={styles.messageContent}>
                  <Avatar
                    src={selectedAgent?.AIAvatar}
                    size={48}
                    className={styles.messageAvatar}
                  />
                  <div className={styles.messageBubble}>
                    <Spin size="small" /> 正在输入...
                  </div>
                </div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>

          {showScrollButton && (
            <Button
              className={styles.scrollButton}
              shape="circle"
              icon={<ArrowDownOutlined />}
              onClick={scrollToBottom}
            />
          )}

          <div className={styles.inputContainer}>
            <div className={styles.inputWrapper}>
              <Input.TextArea
                ref={inputRef}
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                onKeyDown={handleKeyPress}
                placeholder={readOnly ? "当前为只读模式" : "输入消息..."}
                autoSize={{ minRows: 1, maxRows: 20 }}
                className={styles.input}
                onFocus={scrollToBottom}
                variant={"borderless"}
                disabled={readOnly}
              />
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleSendMessage}
                disabled={!inputValue.trim() || sending || readOnly}
                className={styles.sendButton}
              />
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default Chat;
